package com.cloud.base.service.impl;


import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.base.domain.city.*;
import com.cloud.base.mapper.ProvinceCityMapper;
import com.cloud.base.service.IProvinceCityService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dhaigang
 * @since 2023-07-03
 */
@Service("provinceCityService")
public class ProvinceCityServiceImpl extends ServiceImpl<ProvinceCityMapper, ProvinceCity> implements IProvinceCityService {
    @Resource
    private ProvinceCityMapper provinceCityMapper;
    @Resource(name = "myRedis")
    private RedisTemplate<String,Object> redisTemplate;

    public List<Province> getAllProvinceFromDB() {
        List<Province> list = provinceCityMapper.selectGroupByProvince();
        redisTemplate.opsForValue().set("province",list);
        return list;
    }

    public List<Province> getProvinceFromRedis() {
        List<Province> provinceList = (List<Province>) redisTemplate.opsForValue().get("province");
        if (provinceList == null || provinceList.isEmpty()) {
            provinceList = getAllProvinceFromDB();
        }
        return provinceList;
    }
    @Cached(name = "letter2city",cacheType = CacheType.REMOTE)
    public List<Letter2City> getLetter2City(){
       return provinceCityMapper.selectCityList();
    }

    @Cached(name = "province-city::",key = "#provinceCode",cacheType = CacheType.REMOTE)
    public List<City> getCitysByProvinceCode(String provinceCode){
        Province province = new Province();
        province.setProvinceCode(provinceCode);
        return provinceCityMapper.selectGroupByCity(province);
    }

    @Cached(name = "province-city::",key = "#provinceName",cacheType = CacheType.REMOTE)
    public List<City> getCitysByProvinceName(String provinceName){
        Province province = new Province();
        province.setProvinceName(provinceName);
        return provinceCityMapper.selectGroupByCity(province);
    }

    @Cached(name = "city-district::",key = "#cityName",cacheType = CacheType.REMOTE)
    public List<District> selectDistrictByCity(String cityName){
        return provinceCityMapper.selectDistrictByCity(cityName);
    }
}
